<template>
	<view>
		<!-- pages/user/setting/setting.wxml -->
    <navbar></navbar>
		<view class="container">
			<view class="table">
				<!-- <view class="table-cell dis-flex flex-x-between flex-y-center" @tap.stop.prevent="onUpdateAvatar"> -->
				<!-- <view class="table-cell dis-flex flex-x-between flex-y-center">
					<view class="f-28">头像</view>
					<view class="user__avatar">
						<image :src="avatar"></image>
					</view>
				</view> -->
				<view class="table-cell dis-flex flex-x-between flex-y-center" @tap.stop.prevent="onUpdateNickname">
					<view class="f-28">昵称</view>
					<view class="f-32">{{ nickname }}</view>
				</view>
				<view class="table-cell dis-flex flex-x-between flex-y-center" @tap.stop.prevent="nav_cancellation()">
					<view class="f-28">注销</view>
					<!-- <view class="f-32">{{ nickname }}</view> -->
				</view>
			</view>
			<!-- <button v-if="!isWeixin" class="btn-normal btn-logout" @tap.stop.prevent="onLogout" hover-class="hover">退出登录</button> -->
		</view>

		<!-- 复制区块链地址弹窗 -->
		<alert :show="showUpdateNicknameAlert" position="top">
			<form @submit="updateNickname">
				<view class="nickname-alert">
					<view class="f-32">修改昵称</view>
					<view class="m-top20 col-9 f-28">原昵称：{{ nickname }}</view>
					<view class="input-wrapper m-top20">
						<input name="nickname" class="f-28" type="text" placeholder="支持2-16位中英文/数字"
							placeholder-class="input-placeholder-class" />
					</view>
					<view class="alert-bottom">
						<button class="btn-normal btn" hover-class="hover"
							@tap.stop.prevent="onCancelUpdateNickname">取消</button>
						<button form-type="submit" class="btn-normal btn col-m" hover-class="hover"
							:disabled="nicknameUpdateDisabled">确定</button>
					</view>
				</view>
			</form>
		</alert>
	</view>
</template>

<script>
import navbar from "@/components/navbar/navbar";
	import alert from '@/components/alert/index';
    import { isWeixin } from '@/utils/verify.js';
	const app = getApp();
	export default {
		components: {
      navbar,
			alert
		},
		data() {
			return {
				isWeixin:true,
				avatar: '',
				nickname: '',
				showUpdateNicknameAlert: false,
				nicknameUpdateDisabled: false,
				balance:0,
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.getUserDetail();
			this.requestDeta()
      
      //判断当前是否是微信H5
      this.isWeixin = isWeixin();

			this.cropperImageCallback = (filePath) => {
				setTimeout(() => {
					this.updateAvatar(filePath);
				}, 500);
			};
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {},
		methods: {
			requestDeta(){
				// 获取我的钱包
				app._get('user.wallet/index', {}, (res) => {
					this.balance = res.data.userInfo.balance
				});
			},
			nav_cancellation(){
				if(this.balance > 0){
					uni.showModal({
						content: `账户有一笔金额未处理，金额为${this.balance}。暂不支持注销操作`,
						success: (res) => {
							if (res.confirm) {
								try {
									// uni.clearStorageSync();
									// uni.reLaunch({
									// 	url: '/pages/index/index'
									// });
								} catch (e) {
									// Do something when catch error
								}
							}
						}
					});
				}else{
					uni.showModal({
						content: `账户注销后，账户将永久不可在平台使用，是否确定注销？`,
						success: (res) => {
							if (res.confirm) {
								try {
									uni.navigateTo({
										url: './cancellation'
									});
								} catch (e) {
									// Do something when catch error
								}
							}
						}
					});
				}
				
			},
			//////// user tap methods ////////
			onUpdateAvatar: function(e) {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						// tempFilePath可以作为img标签的src属性显示图片
						const tempFilePaths = res.tempFilePaths;
						uni.navigateTo({
							url: `./cropper/cropper?src=${tempFilePaths[0]}`
						});
					}
				});
			},

			onLogout: function(e) {
				uni.showModal({
					content: '确定退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							try {
								uni.clearStorageSync();
								uni.reLaunch({
									url: '/pages/index/index'
								});
							} catch (e) {
								// Do something when catch error
							}
						}
					}
				});
			},

			onUpdateNickname: function(e) {
				this.setData({
					showUpdateNicknameAlert: true
				});
			},

			onCancelUpdateNickname: function(e) {
				this.dismissonUpdateNicknameAlert();
			},

			updateNickname: function(e) {
				this.dismissonUpdateNicknameAlert();
				let {
					nickname
				} = e.detail.value;
				nickname = nickname.replace(/\s+/g, '');

				if (2 > nickname.length || 16 < nickname.length) {
					app.showError('请输入2-16位中英文/数字');
				} else {
					this.setData({
						nicknameUpdateDisabled: true
					});
					uni.showLoading();

					app._post_form(
						'user/updateUser', {
							nickName: nickname
						},
						(res) => {
							if (1 == res.code) {
								uni.hideLoading();
								app.showSuccess(res.msg);
								this.getUserDetail();
							}
						},
						null,
						() => {
							uni.hideLoading();
						}
					);

					this.setData({
						nicknameUpdateDisabled: false
					});
				}
			},

			//////// private methods ////////
			dismissonUpdateNicknameAlert: function() {
				this.setData({
					showUpdateNicknameAlert: false
				});
			},

			/**
			 * 上传图片
			 */
			uploadFile: function(filePath, callBack) {
				uni.showLoading({
					title: '上传中...'
				});

				let params = {
					wxapp_id: app.getWxappId(),
					token: uni.getStorageSync('token')
				}; // 文件上传
				//加密请求头
				let stoken1 = uni.getStorageSync('stoken');
				let stoken = app.unCrypted('20220615_HANGZHOU')
				if(stoken1 != '' ){
					// 加密 正式版需要注释
					stoken = app.unCrypted(new Buffer(stoken1, 'base64').toString('utf8'))
				}
				uni.uploadFile({
					url: `${app.globalData.api_root}upload/image`,
					filePath: filePath,
					name: 'iFile',
					formData: params,
					header: {
						'access-Token': stoken
					},
					complete: (res) => {
						uni.hideLoading();
						let result = typeof res.data === 'object' ? res.data : JSON.parse(res.data);

						if (1 === result.code) {
							if (callBack) {
								callBack(result.data.file_path);
							}
						}
					}
				});
			},

			getUserDetail() {
				app._get('user.index/detail', {}, (result) => {
					if (1 == result.code) {
						let {
							avatarUrl,
							nickName
						} = result.data.userInfo;
						this.setData({
							avatar: avatarUrl,
							nickname: nickName
						});
					}
				});
			},

			updateAvatar: function(filePath) {
				let callback = (avatarUrl) => {
					app._post_form(
						'user/updateUser', {
							avatarUrl: avatarUrl
						},
						(res) => {
							if (1 == res.code) {
								app.showSuccess(res.msg);
								this.getUserDetail();
							}
						}
					);
				};

				this.uploadFile(filePath, callback);
			}
		}
	};
</script>
<style lang="scss" scoped>
	/* pages/user/setting/setting.wxss */
	.container {
		padding: 0 30rpx;
	}

	.btn-logout {
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		border-radius: 44rpx;
		background-color: $uni-bg-color-main;
		margin-top: 130rpx;
		font-size: 28rpx;
		color: #FFF;
		text-align: center;
	}

	.table {
		margin-top: 40rpx;
	}

	.table-cell {
		height: 110rpx;
		padding-right: 20rpx;
		border-bottom: 1px solid #eeeeee;
		position: relative;
	}

	.table-cell:after {
		content: '\e601';
		font-family: 'dy-iconfont';
		color: $uni-text-color;
		font-size: 36rpx;
		position: absolute;
		top: 50%;
		right: -20rpx;
		transform: translateY(-50%);
	}

	.user__avatar {
		width: 88rpx;
		height: 88rpx;
		border-radius: 50%;
		overflow: hidden;
	}

	.user__avatar image {
		width: 100%;
		height: 100%;
	}

	.nickname-alert {
		background: #fff;
		padding-top: 40rpx;
		text-align: center;
	}

	.nickname-alert .input-wrapper {
		padding: 0 40rpx;
	}

	.nickname-alert .input-wrapper input {
		height: 80rpx;
		background-color: #f9f9f9;
		border-radius: 10rpx;
		padding-left: 40rpx;
		text-align: left;
	}

	.nickname-alert .input-placeholder-class {
		color: #ccc;
	}

	.nickname-alert .alert-bottom {
		margin-top: 40rpx;
		border-top: 1px solid #eee;
		overflow: hidden;
		position: relative;
	}

	.nickname-alert .alert-bottom:after {
		content: '';
		width: 1px;
		height: 100%;
		background-color: #eee;
		position: absolute;
		top: 0;
		left: 50%;
		transform: translateX(-50%);
	}

	.nickname-alert .alert-bottom .btn {
		width: 50%;
		height: 100rpx;
		font-size: 28rpx;
		line-height: 100rpx;
		float: left;
	}
</style>
